package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.StartSetmealNotAllowedException;
import com.sky.exception.StoppingDishException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    //保证事务的一致性
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品标插入一条数据,插入后可以返回dishId
        dishMapper.insert(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors!=null&&flavors.size()>0){
           /* flavors.forEach(f->{
                f.setDishId(dishId);
            });*/
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors ,dishId);
        }

    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.page(dishPageQueryDTO);
        long total = page.getTotal();
        List<DishVO> result = page.getResult();
        return new PageResult(total,result);
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    public void deleteBatch(Long[] ids) {

        //判断当前菜品的状态,起售中的菜品不能删除
        //select count(*) from dish where id in(1,2,3) and status;
        Integer countStart=dishMapper.selectByIdsAndStatus(ids);
        if (countStart>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        /*for (Long id : ids) {
            Dish dish=dishMapper.getById(id);
            if (dish.getStatus()== StatusConstant.ENABLE){
                //不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }*/

        //当前菜品是否被套餐关联
        //select count(*) from setmeal_dish where dish_id in(1,2,3);
        Integer countSetmeal= setmealDishMapper.selectByDishId(ids);
        if (countSetmeal>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

       /* List<Long> list = setmealDishMapper.getSetmealIdsByDishId(ids);
        if (list.size()>0&&list!=null){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }*/


        //可以删除,删除菜品中的菜品数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除口味数据
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据id查找菜品和口味
     * @param id
     * @return
     */
    @Override
    public DishVO selectByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);

        //根据id查询口味数据
        List<DishFlavor> flavorList =dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装到Vo

        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavorList);
        return dishVO;
    }

    /**
     * 修改菜品和口味
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        Long dishId = dish.getId();
        //修改菜品表中的基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
           /* flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });*/
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors, dishId);
        }
    }

    /**
     * 修改菜品状态
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //菜品如果想要停售,要先判断菜品关联的套餐是否有起售的状态
        Dish dish = Dish.builder().id(id).status(status)
                .updateTime(LocalDateTime.now()).
                updateUser(BaseContext.getCurrentId()).build();
        if (status==0){
            //获取套餐状态为1的个数
            Integer count= setmealDishMapper.selectStatusSetMealCount(id);
            if (count>0){
                throw new StoppingDishException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL_SHOP);
            }
            else {
                dishMapper.update(dish);
            }
        }else {
            dishMapper.update(dish);
        }
    }

    /**
     * 根据CategoryId查找菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        /*List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;*/
        List<DishVO> dishVOList =dishMapper.listWithFlavor(dish);
        return dishVOList;
    }


}
